// 缓存名称
const CACHE_NAME = 'app-cache-v18';
// 公共前缀
const BASE_PATH = '/project-name';
// 需要缓存的公共路径
const CACHE_APTH = '/api/'

// 给所有客户端发送消息
const sendMessageToAllClients = (message) => {
    self.clients.matchAll().then((clients) => {
        clients.forEach((client) => {
            client.postMessage(message);
        });
    });
};
console.log('加载')
// installl事件：首次注册或更新时
self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME).then((cache) => {
            return cache.addAll([]);
        }).then(() => {
            //  替换了新版本才提示更新
            caches.keys().then((cacheNames) => {
                if (cacheNames.length > 1) {
                    return self.skipWaiting();
                }
            })
        })
    );
});

// active事件：安装完成后或旧版本被替换时
self.addEventListener('activate', (event) => {
    event.waitUntil(
        caches.keys().then((cacheNames) => {
            return Promise.all(
                cacheNames.map((cacheName) => {
                    if (cacheName !== CACHE_NAME) {
                        return caches.delete(cacheName);
                    }
                })
            );
        }).then(() => {
            // 立即获得控制权
            return self.clients.claim();
        })
    );
});

// 监听message消息
self.addEventListener('message', async (event) => {
    console.log('message', event)
});

// 监听fetch事件
self.addEventListener('fetch', (event) => {
    const url = new URL(event.request.url);

    // API 请求走 Service Worker 缓存
    console.log(event.request.method, url.pathname, '------')
    if (event.request.method === 'GET' && url.pathname.indexOf(CACHE_APTH) > -1) {
        event.respondWith(
            caches.match(event.request).then((cachedResponse) => {
                return cachedResponse || fetch(event.request).then(async (response) => {
                    // 只缓存正常的 HTTP 响应 
                    if (!response || response.status !== 200 || response.type !== 'basic') {
                        return response;
                    }
                    const cache = await caches.open(CACHE_NAME);
                    console.log('cach1e', cache, url.pathname);
                    if (response.ok) {
                        cache.put(event.request, response.clone());
                    }
                    return response;
                });
            })
        );
    }
});

// const judgeUpdateHtml = (url: URL) => {
// };